package com.wjjun.customview.views.dropdownmenu;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.luck.picture.lib.tools.ScreenUtils;

import java.util.List;

/**
 * Created by baiiu on 15/12/17.
 * 双列ListView
 */
public class SingleListView<DATA> extends ListView implements AdapterView.OnItemClickListener {

    private BaseBaseAdapter<DATA> mAdapter;
    private OnFilterItemClickListener<DATA> mOnItemClickListener;

    private int check = -1;

    public SingleListView(Context context) {
        this(context, null);
    }

    public SingleListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SingleListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        setDivider(new ColorDrawable(Color.parseColor("#e1e1e1")));
        setDividerHeight(ScreenUtils.dip2px(context, 0.5f));

        setOnItemClickListener(this);
    }


    public SingleListView<DATA> adapter(BaseBaseAdapter<DATA> adapter) {
        this.mAdapter = adapter;
        setAdapter(adapter);
        return this;
    }

    public SingleListView<DATA> onItemClick(OnFilterItemClickListener<DATA> onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
        return this;
    }

    public void setList(List<DATA> list, int checkedPosition) {
        mAdapter.setList(list);

        if (checkedPosition != -1) {
            if (check == checkedPosition) {
                return;
            }
            if (check != -1) {
                setItemChecked(check, false);
            }
            check = checkedPosition;
            setItemChecked(checkedPosition, true);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DATA item = mAdapter.getItem(position);
        check = position;
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(position, item);
        }
    }


}
